<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/16
 * Time: 21:42
 */

namespace App\Library\form_builder\src\view;
use App\Library\form_builder\src\view\Engine\Blade;
class View
{
    //模板所用的编译器引擎
    protected $compiler = null;
    //模板根目录
    protected $base_dir=__DIR__.'/../template';
    //可选目录
    protected $options_dir=__DIR__.'/../template/default/layouts';
    //模板主题
    protected $theme='default';
    //模板主提目录
    protected $base='';
    //模板后缀
    protected $suffix='.html';

    protected $data=[];
    public function __construct()
    {
        $this->base=$this->base_dir.'/'.$this->theme.'/';
        $this->compiler = new Blade();//加载模板
    }

    public function render($componets){

        foreach ($componets as $value){
            $file=$value['component_file'];
            $data=$value['component_data'];
            $filename=$this->base.$file.$this->suffix;//组成文件名

            if(file_exists($filename)){//非空
                if($data) {
                    $this->compiler->replace = array_keys($data);
                    $this->compiler->data=$data;
                    $this->compiler->component_name=$file;
                    $this->compiler->template=file_get_contents($filename);
                    //执行替换
                    $this->compiler->execute();
                    //组件内容写入
                    $this->compiler->write();
                    //return $this->compiler->template;
                }
            }else{
               throw new \Exception($file.'文件不存在');
            }
        }

    }
    public  function form($action,$props=[]){
        $filename=$this->options_dir.'/form.html';
        if(file_exists($filename)){
            $file_content=file_get_contents($filename);
            $this->compiler->load_form($file_content,$action,$props);
        }else{
            throw new \Exception($filename.'文件不存在');
        }
    }
    //加载布局模板并渲染
   public function layout($html){
        $this->compiler->load_layout($html);
   }
   public function submit_button(){
       $filename=$this->options_dir.'/Button.html';
       if(file_exists($filename)){
           $file_content=file_get_contents($filename);
           $this->compiler->load_submit($file_content);
       }else{
           throw new \Exception($filename.'Button文件不存在');
       }

   }
    //获取模板内容
    public  function get_templed(){
        //清除占位符
        $this->compiler->clear_placeholder();
        return $this->compiler->html;
    }
}